package com.ruoyi.controller.system;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.vo.AjaxResult;
import com.ruoyi.common.core.vo.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.controller.BaseController;
import com.ruoyi.domain.SysRole;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.service.SysRoleService;
import com.ruoyi.service.SysUserService;
import com.ruoyi.service.TokenService;

@RestController
@RequestMapping("system/role")
public class SysRoleController extends BaseController{
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysPermissionService sysPermissionService;
	
	@Autowired
    private SysUserService sysUserService;
	
	@Autowired
    private TokenService tokenService;
	/**
	 * 获取角色列表
	 * @param role
	 * @return
	 */
	@GetMapping("list")
	public TableDataInfo list(SysRole role) {
		logger.info("获取角色列表,role:{}",role);
		startPage();
		List<SysRole> list = sysRoleService.selectRoleList(role);
		return getDataTable(list);
	}
	
	/**
	 * 根据角色编号获取详细信息
	 * @param roleId
	 * @return
	 */
	@GetMapping("/{roleId}")
	public AjaxResult getInfo(@PathVariable Long roleId) {
		logger.info("根据角色编号获取详细信息,roleId:{}",roleId);
		return AjaxResult.success(sysRoleService.selectRoleById(roleId));
	}
	
	/**
	 * 新增角色
	 * @param role
	 * @return
	 */
	@PostMapping
	public AjaxResult add(@Validated @RequestBody SysRole role) {
		logger.info("新增角色,role:{}",role);
		if (!sysRoleService.checkRoleNameUnique(role)) {
			return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
		} else if (!sysRoleService.checkRoleKeyUnique(role)) {
			return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
		}
		role.setCreateBy(getUsername());
		return toAjax(sysRoleService.insertRole(role));
		
	}
	
	/**
	 * 修改角色
	 * @param role
	 * @return
	 */
	@PutMapping
	public AjaxResult edit(@Validated @RequestBody SysRole role) {
		logger.info("修改角色,role:{}",role);
		if (!sysRoleService.checkRoleNameUnique(role)) {
			return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
		} else if (!sysRoleService.checkRoleKeyUnique(role)) {
			return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
		}
		role.setUpdateBy(getUsername());
		if (sysRoleService.updateRole(role) > 0 ) {
			LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(sysPermissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(sysUserService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
		}
		return error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
		
	}
	
	/**
	 * 修改保存数据权限
	 * @param role
	 * @return
	 */
	@PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role) {
    	logger.info("修改保存数据权限,role:{}",role);
        sysRoleService.checkRoleAllowed(role);
        sysRoleService.checkRoleDataScope(role.getRoleId());
        return toAjax(sysRoleService.authDataScope(role));
    }
	
	/**
	 * 状态修改
	 * @param role
	 * @return
	 */
	@PutMapping("/changeStatus")
	public AjaxResult changeStatus(@RequestBody SysRole role) {
    	logger.info("状态修改,role:{}",role);
    	sysRoleService.checkRoleAllowed(role);
    	sysRoleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(getUsername());
        return toAjax(sysRoleService.updateRoleStatus(role));
    }
	
	/**
	 * 删除角色
	 * @param roleId
	 * @return
	 */
	@DeleteMapping("/{roleId}")
	public AjaxResult remove(@PathVariable Long roleId) {
		logger.info("删除角色,roleId:{}",roleId);
		return toAjax(sysRoleService.deleteRoleById(roleId));
	}
	

}
